package times

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

type TimeResponse struct {
	UtcOffset    string      `json:"utc_offset"`
	Timezone     string      `json:"timezone"`
	DayOfWeek    int         `json:"day_of_week"`
	DayOfYear    int         `json:"day_of_year"`
	Datetime     time.Time   `json:"datetime"`
	UtcDatetime  time.Time   `json:"utc_datetime"`
	Unixtime     int         `json:"unixtime"`
	RawOffset    int         `json:"raw_offset"`
	WeekNumber   int         `json:"week_number"`
	Dst          bool        `json:"dst"`
	Abbreviation string      `json:"abbreviation"`
	DstOffset    int         `json:"dst_offset"`
	DstFrom      interface{} `json:"dst_from"`
	DstUntil     interface{} `json:"dst_until"`
	ClientIp     string      `json:"client_ip"`
}

// GetNetworkUnixTime 获取网络时间戳，zone 可选 "UTC" 或 "Asia/Shanghai"
func GetNetworkUnixTime(zone string) (int64, error) {
	if zone == "" {
		zone = "UTC"
	}

	url := fmt.Sprintf("https://worldtimeapi.org/api/timezone/%s", zone)
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		return 0, fmt.Errorf("请求失败: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("响应状态错误: %s", resp.Status)
	}

	body, _ := io.ReadAll(resp.Body)
	var result TimeResponse
	if err = json.Unmarshal(body, &result); err != nil {
		return 0, fmt.Errorf("解析响应失败: %v", err)
	}
	return int64(result.Unixtime), nil
}
